{% load geonode_client_tags %}
{% load url from future %}

{% client_viewer_js	%}

<style>
        body {
                padding-top: 0px !important;
        }
        #content {
                position: relative;
        }
        #client-viewer-map {
                position: absolute;
                top: 72px;
                height: calc(100% - 72px);
                width: 100%;
        }
</style>

<script type="text/javascript">
	document.addEventListener('DOMContentLoaded', function () {
    var defaultConfig = {
        authStatus: {% if user.is_authenticated %} 200{% else %} 401{% endif %},
        proxy: '{{ PROXY_URL }}',
        {% if MAPFISH_PRINT_ENABLED %}
        printService: "{{GEOSERVER_BASE_URL}}pdf/",
        {% else %}
        printService: "",
        {% endif %}
        /* The URL to a REST map configuration service.  This service 
         * provides listing and, with an authenticated user, saving of 
         * maps on the server for sharing and editing.
         */
        rest: "{% url "maps_browse" %}",
        ajaxLoginUrl: "{% url "account_ajax_login" %}",
        homeUrl: "{% url "home" %}",
        portalItems: [{
            xtype: "container",
            layout: "fit",
            height: 81,
            region: "north"
        }],
        localGeoServerBaseUrl: "{{ GEOSERVER_BASE_URL }}",
        localCSWBaseUrl: "{{ CATALOGUE_BASE_URL }}",
        csrfToken: "{{ csrf_token }}",
        tools: [{ptype: "gxp_getfeedfeatureinfo"}],
		};
		var config = Object.assign( defaultConfig, {{ config|safe }});
    var options = {mapConfig: config};
    if (config.proxy !== '') {
      options.proxy = "{{PROXY_URL}}";
    }
    if ("{{ MAP_CLIENT_USE_CROSS_ORIGIN_CREDENTIALS }}" == 'True') {
      options.crossOriginCredentials = true;
      var layers = [], urls = [];
      {% for layer in layers %}
      layers[{{ forloop.counter0 }}] = '{{ layer.name }}';
      urls[{{ forloop.counter0 }}] = '{{ layer.ows_url }}';
      {% endfor %}
      for (var i = 0; i < urls.length; i++) {
        // TODO: More robust solution requires CORS policy per layer instead of for whole map
        if (options.crossOriginCredentials == true && urls[i] != 'None') {
            checkUrlCORSCompatible(urls[i]).then(function(response) {
                continue;
            }).catch(function(err){
                console.log("Layer " + layers[i] + "'s service (url: " + urls[i] + ") is not CORS compatible.");
                console.log("Status error: ", err.statusText);
                console.log("Therefore, making all requests anonymously instead of with credentials");
                options.crossOriginCredentials = false;
            });
        }
      }
    } else {
      options.crossOriginCredentials = false;
    }
    var viewer = new window.Viewer('client-viewer-map', options);
    viewer.view();
	});
</script>
<div id="client-viewer-map">
</div>
